<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: 小夏 < 449134904@qq.com>
// | Date: 2019/01/08
// | Time:上午 10:32
// +----------------------------------------------------------------------

namespace api\portal\service;

use api\mall\model\UserLoginMonthModel;
use app\portal\model\UserLevelDefineModel;
use app\portal\model\UserPromoteRelationModel;
use app\portal\model\UserRewardDetailModel;
use app\user\model\UserModel;
use think\facade\Log;
use think\facade\Db;

class UserInfoService
{
    // 更新UserLoginMonthModel 用以统计月活跃
    public function updateUserLoginLog($user)
    {
        // 更新月登录统计
        $userLoginMonthModel = new UserLoginMonthModel();
        $userLoginMonth = $userLoginMonthModel->where('user_id', $user['id'])->where('statistic_month', date('Ym'))->find();
        if (empty($userLoginMonth)) {
            $userLoginMonth = [
                'user_id' => $user['id'],
                'statistic_month' => date('Ym'),
                'login_count' => 1,
            ];
            $userLoginMonthModel->insert($userLoginMonth);
        } else {
            $userLoginMonthModel->where('id', $userLoginMonth['id'])->setInc('login_count');
        }

        $data = [
            'last_login_time' => time(),
            'last_login_ip' => get_client_ip(0, true),
        ];
        $userModel = new UserModel();
        $userModel->where('id', $user['id'])->update($data);

        // 更新七天登录统计
        $login7DayCountArray = cmf_get_option('login_7day_count_array');
        if (empty($login7DayCountArray)) {
            $login7DayCountArray = [];
        }
        // 清除掉七天前的记录
        $last7Day = 'day' . date('Ymd', strtotime('-7 day'));
        if (isset($login7DayCountArray[$last7Day])) {
            unset($login7DayCountArray[$last7Day]);
        }
        $today = 'day' . date('Ymd');
        $curValue = isset($login7DayCountArray[$today]) ? $login7DayCountArray[$today] : 0;
        unset($login7DayCountArray[$today]);
        $login7DayCountArray[$today] = $curValue + 1;
        cmf_set_option('login_7day_count_array', $login7DayCountArray);

        // 更新用户日登录计数 根据last_login_time判断本次登录是否为今日首次登录
        if (date('Ymd') != date('Ymd', $user['last_login_time'])) {
            $userModel->where('id', $user['id'])->setInc('login_day_count');
        }
    }

    // 密码校验
    public function passwordValidate($candidate)
    {
        $r1 = '/[A-Z]/'; //uppercase
        $r2 = '/[a-z]/'; //lowercase
        $r3 = '/[0-9]/'; //numbers
        $r4 = '/[~!@#$%^&*()\-_=+{};:<,.>?]/'; // special char

        if (strlen($candidate) < 8 || 16 < strlen($candidate)) {
            return false;
        }

        $matchCount = 0;
        if (0 < preg_match_all($r1, $candidate, $o)) {
            $matchCount++;
        }
        if (0 < preg_match_all($r2, $candidate, $o)) {
            $matchCount++;
        }
        if (0 < preg_match_all($r3, $candidate, $o)) {
            $matchCount++;
        }
        if (0 < preg_match_all($r4, $candidate, $o)) {
            $matchCount++;
        }
        return $matchCount > 2;
    }

    // 生成激活码
    public function generateActivationCode($length = 6)
    {
        $characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
        $code = '';
        $max = strlen($characters) - 1;

        for ($i = 0; $i < $length; $i++) {
            $code .= $characters[mt_rand(0, $max)];
        }

        return $code;
    }

    // 奖励日志
    public function rewardAddAndLog($userId, $rewardCount, $rewardType, $provideUserId, $remark)
    {
        $mall = cmf_get_option('mall');
        $exchangePercent = min(10000, (isset($mall['exchange_percent']) && !empty($mall['exchange_percent']) ? $mall['exchange_percent'] : 0)) / 100;
        $withdraw = number_format($exchangePercent * $rewardCount / 100, 2);

        $userModel = new UserModel();
        $user = $userModel->where('id', $userId)->find();
        if (empty($user)) {
            Log::info('[ promote ] 没有当前用户信息:' . $userId);
            return;
        }
        $update = [
            'balance' => $user['balance'] + $rewardCount,
            'score' => $user['score'] + $withdraw,
            'coin' => $user['coin'] + $rewardCount - $withdraw,
        ];
        $userModel->where('id', $userId)->update($update);

        $userRewardDetailModel = new UserRewardDetailModel();
        $userRewardDetailModel->insert([
            'user_id' => $userId,
            'reward_count' => $rewardCount,
            'reward_type' => $rewardType,
            'provide_user_id' => $provideUserId,
            'create_time' => time(),
            'remark' => $remark,
        ]);

        Db::name('user_score_log')->insert([            
            'user_id' => $userId,
            'create_time' => time(),
            'balance' => $update['balance'],
            'score' => $withdraw,
            'coin' => $rewardCount - $withdraw,
            // 'action' => $remark . ' 奖励' . $rewardCount . ' 兑换' . $exchangePercent . '%->' . $withdraw . ' 消费' . $rewardCount - $withdraw, 
            'action' => $remark,     
            'type'=>'promote',       
        ]);
    }

    // 实名成功后改变UserPromoteRelationModel用户状态 之后根据直推人数发放奖励并判断升级
    public function userPromoteRelation($userId)
    {
        $userModel = new UserModel();
        $userPromoteRelationModel = new UserPromoteRelationModel();
        $userLevelDefineModel = new UserLevelDefineModel();

        // 改变用户状态
        $userPromoteRelationModel->where('user_id', $userId)->update(['promote_status' => 1]);

        // 查看用户的父用户
        $userPromote = $userPromoteRelationModel->where('user_id', $userId)->find();
        if (empty($userPromote) || $userPromote['parent_id'] == 0) {
            Log::info('[ promote ] 没有当前用户的推广信息:' . $userId);
            return;
        }
        $userParentId = $userPromote['parent_id'];
        $userParent = $userModel->where('id', $userParentId)->find();
        if (empty($userParent)) {
            Log::info('[ promote ] 没有当前用户的父用户信息:' . $userParentId);
            return;
        }
        $userParentPromote = $userPromoteRelationModel->where('user_id', $userParentId)->find();
        if (empty($userParentPromote)) {
            Log::info('[ promote ] 没有当前用户的父用户推广信息:' . $userParentId);
            return;
        }

        $parentCurLevel = $userParent['user_level'];
        $userParentLevelDefine = $userLevelDefineModel->where('user_level', $parentCurLevel)->find();
        $userParentPromoteCount = $userPromoteRelationModel->where('parent_id', $userParentId)->where('promote_status', 1)->count();
        // 直推奖励在完成实名时直接发放
        if ($userParent['user_level'] == 1) {
            // 等级0用户只能获得直推奖励 大于1等级用户只能获得团队奖励且这里只升级 奖励12点再发
            $inviteReward = cmf_get_option('invite_reward');

            // invite_num_加直推人数作为key
            $inviteNumKey = 'invite_num_' . $userParentPromoteCount;
            if (isset($inviteReward[$inviteNumKey])) {
                // 写入奖励记录并加给用户
                $this->rewardAddAndLog($userParentId, $inviteReward[$inviteNumKey], 1, $userId, '成功邀请第' . $userParentPromoteCount . '个人');
            }
        }

        // 父用户团队人数增加
        $userParentTeamSize = $userParentPromote['team_size'] + 1;
        $userPromoteRelationModel->where('user_id', $userParentId)->setInc('team_size');
        $userPromoteRelationModel->where('user_id', $userParentId)->setInc('invite_size');
        // 父用户判断是否升级
        if (!empty($userParentLevelDefine)) {
            if ($userParentPromoteCount >= $userParentLevelDefine['condition_invite'] && $userParentTeamSize >= $userParentLevelDefine['condition_team']) {
                $this->addMedal($userParentId);
                $userModel->where('id', $userParentId)->setInc('user_level');
            }
        }

        // 爷用户团队人数增加
        $userGrandParentId = $userParentPromote['parent_id'];
        if ($userGrandParentId != 0) {
            $userGrandParentPromote = $userPromoteRelationModel->where('user_id', $userGrandParentId)->find();
            if (!empty($userGrandParentPromote)) {
                $userGrandParentTeamSize = $userGrandParentPromote['team_size'] + 1;
                $userPromoteRelationModel->where('user_id', $userGrandParentId)->setInc('team_size');

                // 爷用户判断是否升级 爷用户不用判断直推条件
                $userGrandParent = $userModel->where('id', $userGrandParentId)->find();
                if (!empty($userGrandParent)) {
                    $grandCurLevel = $userGrandParent['user_level'];
                    $userGrandLevelDefine = $userLevelDefineModel->where('user_level', $grandCurLevel)->find();
                    $userGrandPromoteCount = $userPromoteRelationModel->where('parent_id', $userGrandParentId)->where('promote_status', 1)->count();
                    if (!empty($userGrandLevelDefine)) {
                        if ($userGrandPromoteCount >= $userGrandLevelDefine['condition_invite'] && $userGrandParentTeamSize >= $userGrandLevelDefine['condition_team']) {
                            $this->addMedal($userGrandParentId);
                            $userModel->where('id', $userGrandParentId)->setInc('user_level');
                        }
                    }
                }
            }
        }
    }
    
    private function addMedal($uid){
        $model = new UserModel();
        $u = $model->where('id',$uid)->field('user_level')->find();
        if($u){
            $userLevelDefineModel = new UserLevelDefineModel();
            $define = $userLevelDefineModel->where('user_level',$u->user_level)->find();
            if($define && $define->medal_id>0){
                $medalModel = new \api\mall\model\MedalUserModel();
                $old = $medalModel->where('user_id',$uid)->where('medal_id',$define->medal_id)->find();
                if(empty($old)){
                     $medalModel->insert(['user_id'=>$uid,'medal_id'=>$define->medal_id,'status_i'=>0,'create_time'=> time()]);
                }
                
            }
        }
    }

    // 用户邀请信息
    /**
     * invite_size 直推人数
     * team_size 团队人数（直邀下级及间推下级（只到第二级））
     * invite_reward_count 邀请奖励总数
     * team_reward_count 团队奖励总数
     * reward_count 邀请奖励总数+团队奖励总数
     */
    public function userInviteInfo($userId)
    {
        $userPromoteRelationModel = new UserPromoteRelationModel();
        $userRewardDetailModel = new UserRewardDetailModel();
        // 用户推广信息
        $userPromoteRelationData = $userPromoteRelationModel->where('user_id', $userId)->find();
        $userInviteRewardCount = $userRewardDetailModel->where('user_id', $userId)->where('reward_type', 1)->sum('reward_count');
        $userTeamRewardCount = $userRewardDetailModel->where('user_id', $userId)->where('reward_type', 2)->sum('reward_count');

        // // 统计userId的全部直推用户的直推用户数
        // $userIndirectPromoteCount = $userPromoteRelationModel->where('parent_id', 'in', function($query){
        //     $query->name('user_promote_relation')->where('parent_id', $userId)->where('promote_status', 1)->field('user_id');
        // })->where('promote_status', 1)->count();

        return [
            'invite_size' => $userPromoteRelationData['invite_size'],
            'team_size' => $userPromoteRelationData['team_size'],
            'invite_reward_count' => $userInviteRewardCount,
            'team_reward_count' => $userTeamRewardCount,
            'reward_count' => $userInviteRewardCount + $userTeamRewardCount
        ];
    }

    // 更新用户表里面存的用户好友数量
    public function updateUserFriendNum($userId) {
        $api = new \Tencent\TLSSigAPIv2(1600020287, '72bdae2f2efe09bdc5404710fdbe814d23a211dc775af6cbfafa2466f460a9d4');
        $sig = $api->genUserSig('10');
        
        $postUrl = 'https://console.tim.qq.com/v4/sns/friend_get?sdkappid=1600020287&identifier=10&usersig=' 
            . $sig . '&random=' . rand(10000000, 99999999) . '&contenttype=json';

        $curlPost = [
            'From_Account' => "".$userId,
            'StartIndex' => 0,
            'StandardSequence' => 0
        ];
        $curlPost = json_encode($curlPost);
        
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $postUrl);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
        $response = curl_exec($curl);
        curl_close($curl);
        
        Log::info('[ temp ] 请求用户好友数量:' . $response);

        $response = json_decode($response, true);
        if (isset($response['FriendNum'])) {
            $userModel = new UserModel();
            $userModel->where('id', $userId)->update(['friend_num' => $response['FriendNum']]);
            return $response['FriendNum'];
        }
        return 0;
    }
}
